package media_proc

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/media_proc"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type MediaProcService struct {
	service.Service
}

func (e *MediaProcService) CreateMergeScreenTask(d *dto.InsertMergeScreenReq) (int64, error) {
	//urlPath := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room"
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/merge/Insert"
	// 参数
	data := make(map[string]interface{})
	data["task_name"] = d.TaskName
	data["out_url"] = d.OutUrl
	data["out_type"] = d.OutType
	data["scene_info"] = d.SceneInfo
	data["stream_type"] = d.StreamType
	data["template_type"] = d.TemplateType
	data["event_id"] = d.EventId
	data["configs"] = d.Configs
	data["tenant_id"] = d.TenantId
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return 0, err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return 0, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return 0, err
	}
	e.Log.Trace("CreateMergeScreenTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return 0, errors.New(result.Get("message").String())
	}
	return result.Get("data").Int(), nil

}

func (e *MediaProcService) UpdateMergeScreenOutUrl(d *dto.MergeScreenOutUrlUpdateReq) error {
	//urlPath := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room"
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/merge/UpdateOutUrl"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	data["out_url"] = d.OutUrl
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("UpdateMergeScreenOutUrl:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil

}

func (e *MediaProcService) StartMergeScreenTask(d *dto.StartMergeScreenReq) error {
	//urlPath := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room"
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/merge/StartMergeScreenTask"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StartMergeScreenTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil

}

func (e *MediaProcService) StopMergeScreenTask(d *dto.StopMergeScreenReq) error {
	//urlPath := ext.ExtConfig.ServiceConfig.VrcServiceUrl + "/rms/v1/room"
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/merge/StopMergeScreenTask"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StopMergeScreenTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil

}

func (e *MediaProcService) DeleteMergeScreenTask(d *dto.DeleteMergeScreenReq) error {
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/merge/Delete"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("DeleteMergeScreenTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil

}

func (e *MediaProcService) CreateTransTask(d *dto.TransTaskInsertReq) (string, error) {
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/dispatch/CreateDeviceTask"
	// 参数
	data := make(map[string]interface{})
	data["task_name"] = d.TaskName
	data["input_type"] = d.InputType
	data["input_url"] = d.InputUrl
	data["in_de_codec"] = d.InDeCodec
	data["is_deinterlace"] = d.IsDeinterlace
	data["output_type"] = d.OutputType
	data["is_multi"] = d.IsMulti
	data["template_id"] = d.TemplateId
	data["output_url"] = d.OutputUrl
	data["out_codec"] = d.OutCodec
	data["server_ips"] = d.ServerIps

	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return "", err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return "", err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return "", err
	}
	e.Log.Trace("CreateTransTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return "", errors.New(result.Get("message").String())
	}
	return result.Get("data").String(), nil
}

func (e *MediaProcService) DeleteTransTask(d *dto.DeleteTransTaskReq) error {
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/dispatch/RemoveDeviceTask"
	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	data["task_id"] = d.TaskId
	data["forceoffline"] = d.ForceOffline

	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("RemoveDeviceTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *MediaProcService) StartTransTask(d *dto.StartTransTaskReq) error {
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/dispatch/StartDeviceTask"
	// 参数
	data := make(map[string]interface{})
	data["task_id"] = d.TaskId

	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StartTransTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *MediaProcService) StopTransTask(d *dto.StopTransTaskReq) error {
	urlPath := ext.ExtConfig.ServiceConfig.NexaServiceUrl + "/api/v1/dispatch/StopDeviceTask"
	// 参数
	data := make(map[string]interface{})
	data["task_id"] = d.TaskId

	// Marshal
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(string(bytesData))
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StopDeviceTask:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}
	return nil
}
